package com.flying.invest.assets.spider;

import java.io.File;
import java.io.FileFilter;
import java.io.RandomAccessFile;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import org.apache.commons.fileupload.FileItem;

import com.flying.common.annotation.Transaction;
import com.flying.common.util.Codes;
import com.flying.common.util.DateUtils;
import com.flying.common.util.StringUtils;
import com.flying.common.util.Utils;
import com.flying.framework.annotation.Param;
import com.flying.framework.annotation.Service;
import com.flying.framework.data.Data;
import com.flying.framework.model.ActionResult;
import com.flying.framework.model.ModelFactory;
import com.flying.framework.service.AbstractService;
import com.flying.invest.assets.model.Assets;
import com.flying.invest.assets.service.AssetsPriceService;
import com.flying.invest.assets.service.AssetsService;

@Service("InvestingHistoryPriceSpider")
public class InvestingHistoryPriceSpider extends AbstractService {
	private AssetsService assetsService;
	private AssetsPriceService priceService;
	
	public void setAssetsService(AssetsService s) {
		this.assetsService = s;
	}
	public void setAssetsPriceService(AssetsPriceService s) {
		this.priceService = s;
	}

	@Transaction
	public ActionResult upload(Data request) throws Exception {
		FileItem fi = request.get("file");
		String finfo = fi.toString();
		var ss = finfo.split(",");
		String file = null;
		for(String s: ss) {
			var ss2 = s.trim().split("=");
			if("StoreLocation".equals(ss2[0])) {
				file = ss2[1];
			}
		}
		//
		String code = request.getString("code");
		this.importFromFile(code, file);
		//
		return ModelFactory.create(ActionResult.class, Codes.CODE, Codes.SUCCESS);
	}

	@Transaction
	public ActionResult importFromFile(
			@Param("code")String code, 
			@Param("file")String file) throws Exception {
		int lineCount = 0;
		Assets assets = this.assetsService.findByCode(code);
		this.priceService.removeByAssetsId(assets.getAssetsId());
		try(var raf = new RandomAccessFile(file, "rw")) {
			var line = raf.readLine();
			while(line != null) {
				lineCount ++;
				if(lineCount > 1) {
					line = StringUtils.replace(line, "\"", "");
					var items = line.split(",");
					var price_date = DateUtils.formatDate(DateUtils.parseDate(items[0], "yyyy-M-d"), "yyyy-MM-dd");
					var close_price = Double.parseDouble(items[1]);
					var open_price = Double.parseDouble(items[2]);
					var max_price = Double.parseDouble(items[3]);
					var min_price = Double.parseDouble(items[4]);
					if(open_price * close_price * max_price * min_price > 0) {
//						this.priceService.removeByDate(assets.getAssetsId(), price_date);
						this.priceService.create(assets.getAssetsId(), close_price, min_price, max_price, open_price, close_price, price_date, new Date());
					}
				}
				line = raf.readLine();
			}
		}
		return ModelFactory.create(ActionResult.class, Codes.CODE, Codes.SUCCESS, Codes.EFFECT_ROWS, lineCount - 1);
	}
	
	public ActionResult importFromDir(@Param(value = "dir", required=true, desc="文件目录")String dir) throws Exception {
		File fdir = new File(dir);
		final List<String> res = Utils.newArrayList();
		if(fdir.exists() && fdir.isDirectory()) {
			var files = fdir.listFiles(new FileFilter() {
				@Override
				public boolean accept(File pathname) {
					return pathname.getName().toLowerCase().endsWith("csv");
				}
			});
			
			Arrays.stream(files).forEach(f -> {
				try {
					String fn = f.getName();
					fn = fn.substring(0, fn.indexOf("."));
					var r = importFromFile(fn, f.getAbsolutePath());
					res.add(f.getName()+" import success,row count: "+r.getEffectRows());
				} catch (Exception e) {
					res.add(f.getName()+" import fail,reason: "+e);
				}
			});
		}
		return ModelFactory.create(ActionResult.class, Codes.CODE, Codes.SUCCESS, Codes.EFFECT_ROWS, res);
	}
}
